import 'package:flutter/material.dart';
import 'package:svgaplayer_flutter/svgaplayer_flutter.dart';
import 'dart:io';
import 'dart:typed_data';
import 'package:path/path.dart' as path;
import 'package:path_provider/path_provider.dart';
import 'dart:ui';

// SVGA视图模型
class SVGAViewModel extends ChangeNotifier {
  List<File> _frames = [];
  int _currentFrameIndex = 0;
  bool _isDragging = false;
  File? _svgaFile;
  String? _currentFileName;
  double _fps = 0;
  double _duration = 0;
  double _memoryUsage = 0;
  int _totalFrames = 0;
  int _width = 0;
  int _height = 0;
  bool _isProcessing = false; // 防止重复解析

  List<File> get frames => _frames;
  int get currentFrameIndex => _currentFrameIndex;
  bool get isDragging => _isDragging;
  File? get currentFrame => _frames.isNotEmpty ? _frames[_currentFrameIndex] : null;
  File? get svgaFile => _svgaFile;
  String? get currentFileName => _currentFileName;
  double get fps => _fps;
  double get duration => _duration;
  double get memoryUsage => _memoryUsage;
  int get totalFrames => _totalFrames;
  int get width => _width;
  int get height => _height;
  bool get isProcessing => _isProcessing;

  /// 清理所有状态
  Future<void> clearState() async {
    debugPrint('开始清理状态...');
    _frames.clear();
    _currentFrameIndex = 0;
    _svgaFile = null;
    _currentFileName = null;
    _fps = 0;
    _duration = 0;
    _memoryUsage = 0;
    _totalFrames = 0;

    try {
      final tempDir = await getTemporaryDirectory();
      final framesDir = Directory('${tempDir.path}/svga_frames');
      if (await framesDir.exists()) {
        await framesDir.delete(recursive: true);
        debugPrint('临时目录已删除');
      }
    } catch (e, stackTrace) {
      debugPrint('清理临时目录失败: $e\n$stackTrace');
    }

    notifyListeners();
    debugPrint('状态清理完成');
  }

  void setDragging(bool value) {
    if (_isDragging != value) {
      _isDragging = value;
      notifyListeners();
    }
  }

  void setCurrentFrameIndex(int index) {
    if (index >= 0 && index < _frames.length && index != _currentFrameIndex) {
      _currentFrameIndex = index;
      notifyListeners();
    }
  }

  /// 解析 SVGA 文件
  Future<void> processSVGAFile(String filePath) async {
    if (_isProcessing) {
      debugPrint('SVGA 解析正在进行中，跳过本次调用');
      return;
    }
    _isProcessing = true;

    debugPrint('开始处理 SVGA 文件: ${path.basename(filePath)}');

    try {
      await clearState();
      
      imageCache.clear();
      imageCache.clearLiveImages();
      debugPrint('图片缓存已清空');

      _currentFileName = path.basename(filePath);

      final tempDir = await getTemporaryDirectory();
      final framesDir = Directory('${tempDir.path}/svga_frames');
      if (await framesDir.exists()) {
        await framesDir.delete(recursive: true);
      }
      await framesDir.create(recursive: true);
      debugPrint('创建新的临时目录: ${framesDir.path}');

      _svgaFile = File(filePath);
      debugPrint('设置新的 SVGA 文件路径: ${_svgaFile?.path}');

      final parser = SVGAParser();
      final videoItem = await parser.decodeFromBuffer(await _svgaFile!.readAsBytes());
      debugPrint('SVGA 文件解析完成');

      _totalFrames = videoItem.params.frames;
      _fps = videoItem.params.fps.toDouble();
      _duration = _totalFrames / _fps;
      _width = videoItem.params.viewBoxWidth.toInt();
      _height = videoItem.params.viewBoxHeight.toInt();

      final images = videoItem.images;
      debugPrint('开始提取帧图片，总数：${images.length}');

      final List<Future<File?>> frameFutures = images.entries.map((entry) async {
        if (entry.value.isNotEmpty) {
          try {
            final codec = await instantiateImageCodec(Uint8List.fromList(entry.value));
            final frame = await codec.getNextFrame();
            final byteData = await frame.image.toByteData(format: ImageByteFormat.png);

            if (byteData != null) {
              final frameFile = File('${framesDir.path}/${entry.key}');
              await frameFile.writeAsBytes(byteData.buffer.asUint8List());

              // 计算内存占用，仅在 Debug 模式下打印
              _memoryUsage += (frame.image.width * frame.image.height * 4) / (1024 * 1024);
              debugPrint('帧 ${entry.key} 内存占用: ${_memoryUsage.toStringAsFixed(2)} MB');

              return frameFile;
            }
          } catch (e, stackTrace) {
            debugPrint('处理帧 ${entry.key} 时出错: $e\n$stackTrace');
          }
        }
        return null;
      }).toList();

      _frames = (await Future.wait(frameFutures)).whereType<File>().toList();

      if (_frames.isEmpty) {
        debugPrint('未能从 SVGA 文件中提取到任何图片');
        await clearState();
      } else {
        debugPrint('成功提取了 ${_frames.length} 帧图片');

        imageCache.clear();
        imageCache.clearLiveImages();
        debugPrint('再次清空图片缓存');

        _currentFrameIndex = 0;
        notifyListeners();
        debugPrint('UI 更新完成');
      }
    } catch (e, stackTrace) {
      debugPrint('处理 SVGA 文件时出错: $e\n$stackTrace');
      await clearState();
    } finally {
      _isProcessing = false;
    }
  }
}
